package com.mockingjay.service;

import com.spring.BeanPostProcessor;
import com.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author mockingjay
 * @date 2023/5/8 - 21:02
 */
@Component("BeanPostProcessorTest")
public class BeanPostProcessorTest implements BeanPostProcessor {


    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {

        /*if(beanName.equals("userService")){
            ((UserService)bean).setName("mockingjay is good");
        }*/

        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        //匹配
        System.out.println(beanName);
        if(beanName.equals("productService")){
            // 生成代理类
           Object proxyInstance=Proxy.newProxyInstance(BeanPostProcessorTest.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
               @Override
               public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                   System.out.println("代理逻辑");
                   method.invoke(bean,args);
                   return null;
               }
           });
            return proxyInstance;
        }
        return bean;
    }
}
